package apple.eclipse.actions;

import java.io.IOException;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;

import apple.core.Apple;
import apple.eclipse.model.Model;
import apple.eclipse.views.MonitorView;
import apple.ui.swt.Keyboard;
import apple.ui.swt.Monitor;

public class CreateAction extends Action {

   public static final String ID = "javapple2.create";

   private static int secondaryId = 0;

   private IWorkbenchWindow window;

   public CreateAction(IWorkbenchWindow window) {
      this.window = window;
      setId(ID);
      setText("&Create");
      setToolTipText("Create an emulator");
   }

   public void run() {

      try {

         IViewPart viewPart = window.getActivePage().showView(MonitorView.ID,
               String.valueOf(secondaryId++), IWorkbenchPage.VIEW_ACTIVATE);

         window.getActivePage().addPartListener(new IPartListener() {
            public void partActivated(IWorkbenchPart part) {

            }

            public void partBroughtToTop(IWorkbenchPart part) {

            }

            public void partClosed(IWorkbenchPart part) {

            }

            public void partDeactivated(IWorkbenchPart part) {

            }

            public void partOpened(IWorkbenchPart part) {

            }
         });

         MonitorView view = (MonitorView) viewPart;

         Monitor monitor = view.getMonitor();
         Keyboard keyboard = view.getKeyboard();
         final Apple apple = new Apple("Christiaan's Apple IIe");
         keyboard.setKeyboardDecoder(apple.getKeyboardDecoder());
         apple.setMonitor(monitor);
         monitor.setApple(apple);
         Model.getInstance().addApple(apple);
      } catch (PartInitException e) {
         MessageDialog.openError(window.getShell(), "Error", e
               .getLocalizedMessage());
      } catch (IOException e) {
         MessageDialog.openError(window.getShell(), "Error", e
               .getLocalizedMessage());
      }
   }
}
